# cogs/uptime.py
import requests
from discord.ext import tasks


class yuanshen:

  def __init__(self, client):
    self.client = client
    self.cookie = ''
    self.interval = None
    self.expect_cookie = False
    self.timer.start()

  def cog_unload(self):
    self.timer.cancel()

  async def my_on_message(self, message):
    if message.author.bot:
      return False

    if self.expect_cookie:
      self.cookie = message.content
      self.expect_cookie = False
      await message.channel.send('Cookie 设置成功.')
      return True
    elif message.content.startswith('#填写cookie'):
      self.expect_cookie = True
      await message.channel.send('请发送cookie.')
      return True
    elif message.content.startswith('#定时'):
      try:
        hours = int(message.content[3:].replace('h', ''))
        self.interval = hours * 60 * 60
        await message.channel.send(f'每 {hours} 小时发送一次包.')
        return True
      except ValueError:
        await message.channel.send('命令格式错误：请输入"#定时[小时数]h"（例如："#定时24h"）')
        return True
    elif message.content.startswith('#发包'):
      response = self.send_request()
      if not response.ok:
        await message.channel.send('cookie可能已失效!')
      else:
        await message.channel.send(response.text)
      return True
    return False

  @tasks.loop(seconds=0)
  async def timer(self):
    if self.interval is not None:
      self.timer.change_interval(seconds=self.interval)
      response = self.send_request()
      if not response.ok:
        await self.client.get_channel('channel-id').send('cookie可能已失效!')
      else:
        await self.client.get_channel('channel-id').send('Cookie 仍有效.')
    else:
      self.timer.change_interval(seconds=60 * 60 * 24)

  def send_request(self):
    url = 'https://uptimerobot.com/inc/dml/monitorDML.php?action=resetMonitor&monitorID=794637679'
    cookies = {"PHPSESSID": self.cookie}
    return requests.get(url, cookies=cookies)
